import type { Context } from 'koa';
import { SigninDto } from '@/dtos/signin.dto';
import { UserService } from '@/services/user';
import { pwdDecrypt } from '@/helpers/encryption';
import { generateToken } from '@/helpers/generateToken';
import { ResponseErrors, NoPermissionErrors } from '@/enums/responseErrors';
import { UserRoles } from '@/enums/userEnums';

// 用户登录
export const signinController = async (ctx: Context) => {
  const input = ctx.request.body;
  const params = await ctx.vailParams<SigninDto>(SigninDto, input);
  
  const user = await UserService.findUserByAcnt(params.account);

  // 账户不存在
  if (!user) {
    ctx.sendError(ResponseErrors.userNotExist);
    return;
  }

  // 是后台管理系统
  if (ctx.platform === 'adminSystem') {
    if (user.role !== UserRoles.admin) {
      ctx.sendError(NoPermissionErrors.userNoPermission);
      return;
    }
  }

  // 密码校验
  if (!pwdDecrypt(params.password, user.password)) {
    return ctx.sendError(ResponseErrors.acntOrPwdIncorrect);
  }

  const result = generateToken({
    userId: user._id,
    createAt: Date.now()
  });

  delete user.password;
  ctx.sendSuccess({
    ...result,
    userInfo: user
  });
}